﻿using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace _3_Controllers
{
	/// <summary>
	/// 这个类可以实现自己对接口和实现的定义，这里实现默认引用接口和引用实现的注入
	/// </summary>
	public class AutoFacModule : Autofac.Module
	{
		/// <summary>
		/// 自动注入
		/// </summary>
		/// <param name="builder"></param>
		protected override void Load(ContainerBuilder builder)
		{
			////注册当前程序集中以“Service”及“Repository”结尾的类,暴漏类实现的所有接口，生命周期为PerLifetimeScope
			//以“Service”及“Repository”结尾的类是利用发型实现的数据仓库的管理及业务处理的类和接口
			builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
			builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerLifetimeScope();

			//WebAPI只用引用services和repository的接口，不用引用实现的dll。
			//如需加载实现的程序集，将dll拷贝到bin目录下即可，不用引用dll
			var iServices = Assembly.Load("1_Interfaces");
			var services = Assembly.Load("2_Services");

			//根据名称约定（服务层的接口和实现均以Services结尾），实现服务接口和服务实现的依赖
			builder.RegisterAssemblyTypes(iServices, services)
				.Where(t => t.Name.EndsWith("Service"))
				.AsImplementedInterfaces().PropertiesAutowired();

			builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces().PropertiesAutowired().AsSelf();
		}
	}
}
